<template>
  <div class="userInfo">
    <van-nav-bar
      title="个人信息"
      left-arrow
      @click-left="leftClick"
    ></van-nav-bar>
    <van-cell-group>
      <van-uploader
        :after-read="afterRead"
        :before-read="beforeRead"
        style="width:100%"
      >
        <van-cell title="头像" is-link :value="userInfo.photo" center>
          <img class="cover" :src="userInfo.photo" alt="" />
        </van-cell>
      </van-uploader>
      <van-cell title="昵称" :value="userInfo.name" is-link></van-cell>
      <van-cell title="简介" :value="userInfo.intro" is-link></van-cell>
    </van-cell-group>
    <van-cell class="spliceCell"></van-cell>
    <van-cell-group class="cell2">
      <van-cell
        @click="genderClick"
        title="性别"
        :value="{ 0: '男', 1: '女', 2: '未知' }[userInfo.gender]"
        is-link
      ></van-cell>
      <van-cell
        title="生日"
        class="birthday"
        :value="userInfo.birthday | formatTime"
        is-link
        @click="birthdayClick"
      ></van-cell>
    </van-cell-group>
    <div class="logout" @click="logout">
      <span>退出登录</span>
    </div>
    <!-- 性别选项 动作面板 cancel点击取消触发的事件 点击选项触发的事件-->
    <van-action-sheet
      v-model="showGender"
      :actions="actions"
      cancel-text="取消"
      @cancel="showGender = false"
      @select="genderSelect"
    >
    </van-action-sheet>
    <!-- 生日选择 -->
    <van-popup position="bottom" v-model="showDate">
      <van-datetime-picker
        v-model="currentTime"
        type="date"
        title="选择年月日"
        :min-date="minDate"
        :max-date="maxDate"
        @cancel="showDate = false"
        @confirm="dateConfirm"
      >
      </van-datetime-picker>
    </van-popup>
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import dayjs from 'dayjs'
import { userProfilePatch, userPhotoPatch } from '@/api/user.js'
// import Dialog from 'vant'
export default {
  data () {
    return {
      minDate: new Date('1950-01-01'), // 最小日期
      maxDate: new Date(), // 最大的日期-当前年月日
      currentTime: new Date(),
      showDate: false,
      showGender: false, // 是否显示动作面板
      actions: [
        // 动作面板的选项
        {
          name: '男',
          value: 0
        },
        {
          name: '女',
          value: 1
        }
      ]
    }
  },
  computed: {
    ...mapState('user', ['userInfo'])
    // ...mapState('user', {
    //   user: 'userInfo'
    // })
  },
  filters: {
    formatTime (time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  created () {
    this.$store.dispatch('user/getUserInfo')
  },
  methods: {
    ...mapMutations('user', ['getState', 'editUserInfo']),
    leftClick () {
      this.$router.push('/user')
    },
    // 退出点击
    logout () {
      // 提示用户是否删除
      this.$dialog
        .confirm({
          title: '提示',
          message: '您确定要退出吗？'
        })
        .then(() => {
          // 删除token
          this.getState('')
          // 跳转到首页
          this.$router.push('/')
          this.$toast.success('退出成功')
        })
        .catch(() => {})
    },
    // 选择性别 item为：触发select事件会获取到当前项数据，固定参数
    async genderSelect (item) {
      console.log(item)
      this.showGender = false
      //  调用方法修改个人资料
      this.editUserInfos({
        key: 'gender',
        value: item.value
      })
      //   const res = await userProfilePatch({
      //     gender: item.value
      //   })
      //   //  调用vuex中的mutations方法修改性别
      //   this.editUserInfo({
      //     key: 'gender',
      //     value: item.value
      //   })
      //   console.log(res)
    },
    // 性别点击
    genderClick () {
      this.showGender = true
      //  将当前选中的项禁用
      this.actions[this.userInfo.gender].disabled = true
      //  将原来禁用的性别还原
      this.actions[1 - this.userInfo.gender].disabled = false
    },
    // 选择生日
    birthdayClick () {
      this.showDate = true
      this.currentTime = new Date(this.userInfo.birthday)
    },
    // 选择生日后点击确定
    dateConfirm () {
      this.showDate = false
      //  修改生日日期
      this.editUserInfos({
        key: 'birthday',
        value: this.currentTime
      })
    },
    // 优化修改个人信息
    async editUserInfos (obj) {
      await userProfilePatch({
        [obj.key]: obj.value
      })
      this.editUserInfo({
        key: obj.key,
        value: obj.value
      })
      this.$toast.success('修改成功')
    },
    async afterRead (response) {
      const _form = new FormData()
      _form.append('photo', response.file)
      const res = await userPhotoPatch(_form)
      //  修改vuex中的数据
      this.editUserInfo({ key: 'photo', value: res.data.photo })
      this.$toast.success('上传成功')
      console.log('上传图片返回的数据', res)
    },
    beforeRead (file) {
      const _file = file.type === 'image/png' || file.type === 'image/jpeg'
      const _size1m = file.size / 1024 / 1024 < 1
      if (!_file) {
        this.$toast.fail('请上传png、jpeg格式的图片')
      }
      if (!_size1m) {
        this.$toast.fail('请上传1MB以内的图片')
      }
      return _file && _size1m
    }
  }
}
</script>

<style lang="less" scoped>
.userInfo {
  //   background-color: #f8f8f8;
  .spliceCell {
    background-color: #f8f8f8;
  }
}
.cell2 {
  //   margin-top: 15px;
}
.cover {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  vertical-align: middle; // 图片居中对齐
}
.logout {
  position: absolute;
  bottom: 20px;
  left: 50%;
  margin-left: -52.68px;
  padding: 10px;
  font-size: 14px;
  color: @geek-color;
}
::v-deep .van-uploader__input-wrapper {
  width: 100%;
}
</style>
